package com.meiyuetao.util;

import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.ss.usermodel.*;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by Administrator on 2016/2/20.
 */
public class ExcelUtil {

    /**
     * 读取xls文件内容
     *
     * @param excel
     * @return
     * @throws IOException
     * @throws InvalidFormatException
     */
    public static List<Row> readXls(File excel) throws IOException, InvalidFormatException {
        InputStream is = new FileInputStream(excel);
        Workbook workbook = WorkbookFactory.create(is);
        // Map<String, String> data = new HashMap<String, String>();
        // 循环工作表Sheet
        List<Row> rows = new ArrayList<Row>();
        for (int numSheet = 0; numSheet < workbook.getNumberOfSheets(); numSheet++) {
            Sheet sheet = workbook.getSheetAt(numSheet);
            if (sheet == null) {
                continue;
            }
            // 循环行Row
            for (int rowNum = 1; rowNum <= sheet.getLastRowNum(); rowNum++) {
                Row row = sheet.getRow(rowNum);
                if (row != null) {
                    rows.add(row);
                }
            }
        }
        return rows;
    }

    /**
     * 得到Excel表中的值
     *
     * @param cell
     * @return
     */
    @SuppressWarnings("static-access")
    public static String getValue(Cell cell) {
        if (cell == null) {
            return "";
        } else if (cell.getCellType() == cell.CELL_TYPE_BOOLEAN) {
            // 返回布尔类型的值
            return String.valueOf(cell.getBooleanCellValue());
        } else if (cell.getCellType() == cell.CELL_TYPE_NUMERIC) {
            // 返回数值类型的值
            // return String.format("%.0f", cell.getNumericCellValue());
            DecimalFormat df = new DecimalFormat("0");
            return df.format(cell.getNumericCellValue());
        } else {
            // 返回字符串类型的值
            return String.valueOf(cell.getStringCellValue());
        }
    }
}
